package com.asset.dispoal.defaultDepartment.service.commom;

import com.asset.dispoal.defaultDepartment.domain.db.entity.GbDefaultDepartment;
import com.asset.dispoal.defaultDepartment.domain.db.mapper.GbDefaultDepartmentMapper;
import com.asset.dispoal.defaultDepartment.dto.GbDefaultDepartmentResponse;
import com.asset.dispoal.defaultDepartment.service.converter.GbDefaultDepartmentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/3/21$
 */
@Component
public class GbDefaultDepartmentQueryCommand implements BaseCommand<String, Result> {

    @Autowired
    GbDefaultDepartmentMapper defaultDepartmentMapper;


    @Override
    public Result<List<GbDefaultDepartmentResponse>> execute(String companyType) {
        List<GbDefaultDepartment> gbDefaultDepartments = defaultDepartmentMapper.queryAllByCompanyType(companyType);
        List<GbDefaultDepartmentResponse> gbDefaultDepartmentResponses = GbDefaultDepartmentConverter.INSTANCE.doToRes(gbDefaultDepartments);
        List<GbDefaultDepartmentResponse> departmentList = gbDefaultDepartmentResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        for (GbDefaultDepartmentResponse departmentResponses : departmentList) {
            recursion(gbDefaultDepartmentResponses, departmentResponses);
        }
        List<GbDefaultDepartmentResponse> responseList = gbDefaultDepartmentResponses.stream().filter(item -> StringUtil.isBlank(item.getParentId())).collect(Collectors.toList());
        return Result.ok(responseList);
    }

    private void recursion(List<GbDefaultDepartmentResponse> collect, GbDefaultDepartmentResponse departmentResponse) {
        for (GbDefaultDepartmentResponse response : collect) {
            if (departmentResponse.getId().equals(response.getParentId())) {
                departmentResponse.getDepartmentList().add(response);
                recursion(collect, response);
            }
        }
    }
}
